#version 150

in vec4 color;
out vec4 fcolor;

in vec3 pos;
in vec3 N,L,E,H;
uniform vec4 AmbientProduct, DiffuseProduct, SpecularProduct;

uniform float Shades;
uniform int flag;
uniform int selectionColorR;
uniform int selectionColorG;
uniform int selectionColorB;
uniform int selectionColorA;
uniform float Shininess;


int discretize(float val, float min, float max, int nbins)
{
    return (int((val - min) / (max - min) * float(nbins)));
}

float undiscretize(int dis, float min, float max, int nbins)
{
        return float(dis) / float(nbins) * (max - min) + min;
}


void main()
{
    vec4 diffuse, specular;
    float shadef ;
    int shadei;

    float Kd = max( 0.0, dot(L, N) );

    // calculate fragment intensity
    float intensity = dot(E,N);
    float silhouette_threshold = 0.3;

    // first assume fragment is a silhouette
    int step = 0;
    diffuse = 0 * DiffuseProduct;
        
    // Then if the intesity is higher than given threshold 
    if (intensity > silhouette_threshold)
    {

        // scale the diffuse element by the discretized intensity

        // since black is one of our shades, do we want fewer 1 discrete steps?
        
        // calculate a discrete shade bin from intesity 
        shadei = discretize(intensity*Kd,silhouette_threshold,1,int(Shades));

        // calculate discrete intensity from given shade number
        shadef = undiscretize(shadei,silhouette_threshold,1,int(Shades));

        diffuse = shadef * DiffuseProduct;

    }

    // just leave off the specular altogether. It looks odd when toonified.
    //float Ks = pow( max(dot(N, H), 0.0), Shininess );
    //specular = shadef * Ks * SpecularProduct;
    //if( dot(L, N) < 0.0 )
	//{
	//	specular = vec4(0.0, 0.0, 0.0, 1.0);
    //}

    
    if(flag == 1)
    {
        fcolor.r = float(selectionColorR)/float(255);
        fcolor.g = float(selectionColorG)/float(255);
        fcolor.b = float(selectionColorB)/float(255);
        fcolor.a = float(selectionColorA)/float(255);
    }
    else
    {
        // just leave off the specular altogether. It looks odd when toonified.
        //fcolor = diffuse + specular;
        fcolor = diffuse;
        fcolor.a = 1.0;
    }
}


